package com.smec.moblie.adapter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.smec.moblie.R;
import com.smec.moblie.activity.ElectronicFenceMapActivity;
import com.smec.moblie.activity.MainDetailActivity;
import com.smec.moblie.bean.MaintenanceBean;
import com.smec.moblie.common.ConstValue;
import com.smec.moblie.control.EventCenter;
import com.smec.moblie.location.ServiceUtil;
import com.smec.moblie.util.Util;
import com.smec.moblie.view.RippleView;

import java.util.ArrayList;

import de.greenrobot.event.EventBus;

/**
 * 保养工单列表adapter
 */
public class MainListAdapter extends BaseAdapter implements ConstValue {

    private static ArrayList<MaintenanceBean> mainListBeen = new ArrayList<MaintenanceBean>();
    private static Context context;

    private String lo;
    private String la;

    public MainListAdapter(Context context) {
        MainListAdapter.context = context;
    }

    public void setList(ArrayList<MaintenanceBean> mainListBeen) {
        this.mainListBeen = mainListBeen;
        notifyDataSetChanged();
    }

    public ArrayList<MaintenanceBean> getList() {
        return mainListBeen;
    }

    @Override
    public int getCount() {
        return mainListBeen.size();
    }

    @Override
    public Object getItem(int position) {
        return mainListBeen.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        View view;
        if (convertView == null) {
            view = LayoutInflater.from(context).inflate(R.layout.item_mainlist, null);
        } else {
            view = convertView;
        }

        TextView item1 = (TextView) view.findViewById(R.id.item1);
        TextView item2 = (TextView) view.findViewById(R.id.item2);
        TextView item3 = (TextView) view.findViewById(R.id.item3);
        TextView item4 = (TextView) view.findViewById(R.id.item4);

        TextView mntschdateTv = (TextView) view.findViewById(R.id.mntschdateTv);
        TextView mnttimerangecodeTv = (TextView) view.findViewById(R.id.mnttimerangecodeTv);
        RippleView mainlistRippleView = (RippleView) view.findViewById(R.id.mainlistRippleView);
        CardView cardView = (CardView) view.findViewById(R.id.cardView);
        Button listactionBtn = (Button) view.findViewById(R.id.listactionBtn);

        TextView finishedTimeTv = (TextView) view.findViewById(R.id.finishedTimeTv);
        ImageView finishedTimeImg = (ImageView) view.findViewById(R.id.finishedTimeImg);

        LinearLayout linearlayout_daytime = (LinearLayout) view.findViewById(R.id.linearlayout_daytime);

        listactionBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                new MyOnClickListener(position, finishedTimeTv, finishedTimeImg, listactionBtn)
                gotoActivity(position);
            }
        });
        mainlistRippleView.setRippleDuration(100);//设置水波时间
        mainlistRippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
            @Override
            public void onComplete(RippleView rippleView) {
                gotoActivity(position);
            }
        });
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoActivity(position);
            }
        });

        MaintenanceBean maintenanceBean = mainListBeen.get(position);
        item1.setText(maintenanceBean.getWorkorder_no());
        item2.setText(maintenanceBean.getBUILDING_NAME());
        item3.setText(maintenanceBean.getELE_LOCAL_NAME());
        item4.setText(maintenanceBean.getLoc_address());

        mntschdateTv.setText(Util.generateSchTime(maintenanceBean.getMNT_SCH_DATE()));
        mnttimerangecodeTv.setText(Util.generateSchTimeCode(maintenanceBean.getMNT_TIMERANGE_CODE()));

        if ("COMPLETED".equals(maintenanceBean.getWo_status_code())) {
            listactionBtn.setVisibility(View.GONE);

            finishedTimeTv.setText(Util.conversionStr(maintenanceBean.getFinish_date()) + " 完成");
            finishedTimeImg.setVisibility(View.VISIBLE);

            maintenanceBean.setOrderCode(ORDER_FINISH);
            maintenanceBean.update(maintenanceBean.getId());
            MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
            maintenanceBeanTemp.setOrderCode(ORDER_FINISH);
            maintenanceBeanTemp.update(maintenanceBean.getId());


        } else {
            if ("SUBMITTED_WITHOUT_IMG".equals(maintenanceBean.getWo_status_code())) {
                MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                maintenanceBeanTemp.setOrderCode(ORDER_SUBMIT_WITHOUT_IMAGE);
                maintenanceBeanTemp.update(maintenanceBean.getId());
                maintenanceBean.setOrderCode(ORDER_SUBMIT_WITHOUT_IMAGE);
            } else if ("STATION_REJECT".equals(maintenanceBean.getWo_status_code())) {
                MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                maintenanceBeanTemp.setOrderCode(ORDER_STATION_REJECT);
                maintenanceBeanTemp.update(maintenanceBean.getId());
                maintenanceBean.setOrderCode(ORDER_STATION_REJECT);
            }
            listactionBtn.setVisibility(View.VISIBLE);
            setlistaction(position, listactionBtn, finishedTimeTv, finishedTimeImg);

        }

        if (Util.generateSchTime(Util.getSystemDateNow()).equals(Util.generateSchTime(maintenanceBean.getMNT_SCH_DATE()))) {
            linearlayout_daytime.setBackgroundResource(R.mipmap.maint_list_daytime_today);
        } else {
            linearlayout_daytime.setBackgroundResource(R.mipmap.maintlist_daytime);
        }

        return view;
    }


    /**
     * 设置OrderCode状态
     *
     * @param position
     * @param listactionBtn
     * @param finishedTimeTv
     * @param finishedTimeImg
     */
    private void setlistaction(int position, Button listactionBtn, TextView finishedTimeTv, ImageView finishedTimeImg) {
        MaintenanceBean maintenanceBean = mainListBeen.get(position);
        int orderCode = maintenanceBean.getOrderCode();
        if ("".equals(maintenanceBean.getDeparture_date())) {
            orderCode = ORDER_STARTOFF;
        }
        if (!"".equals(maintenanceBean.getDeparture_date())) {
            orderCode = ORDER_ARRIVE;
        }
        if (!"".equals(maintenanceBean.getOnsite_date())) {
            orderCode = ORDER_SUBMITINFORMATION;
        }
        if ("SUBMITTED_WITHOUT_IMG".equals(maintenanceBean.getWo_status_code())) {
            orderCode = ORDER_SUBMIT_WITHOUT_IMAGE;
        }
        if ("STATION_REJECT".equals(maintenanceBean.getWo_status_code())) {
            orderCode = ORDER_STATION_REJECT;
        }

        maintenanceBean.setOrderCode(orderCode);
        MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
        maintenanceBeanTemp.setOrderCode(orderCode);
        maintenanceBeanTemp.update(maintenanceBean.getId());
        String listaction = "";
        String time = "";
        switch (orderCode) {
            case ORDER_STARTOFF:
                listaction = "开始出发";
                listactionBtn.setBackgroundResource(R.drawable.selector_listitem_buttonblue);
                break;
            case ORDER_ARRIVE:
                listaction = "到达现场";
                time = Util.changeToHHmm(maintenanceBean.getDeparture_date()) + " 出发";
                listactionBtn.setBackgroundResource(R.drawable.selector_listitem_buttonblue);
                break;
            case ORDER_SUBMITINFORMATION:
                listaction = "提交信息";
                time = Util.changeToHHmm(maintenanceBean.getOnsite_date()) + " 到达";
                listactionBtn.setBackgroundResource(R.drawable.selector_listitem_buttongreen);
                break;
            case ORDER_SUBMIT_WITHOUT_IMAGE:
                listaction = "照片补传";
                time = Util.changeToHHmm(maintenanceBean.getLeave_date()) + " 提交";
                listactionBtn.setBackgroundResource(R.drawable.selector_listitem_buttonyellow);
                break;
            case ORDER_STATION_REJECT:
                listaction = "驳回重新提交";
                time = Util.changeToHHmm(maintenanceBean.getLeave_date()) + " 提交";
                listactionBtn.setBackgroundResource(R.drawable.selector_listitem_buttonred);
                break;
            default:
                break;
        }
        listactionBtn.setText(listaction);
        finishedTimeTv.setText(time);
        if ("".equals(time)) {
            finishedTimeImg.setVisibility(View.INVISIBLE);
        } else {
            finishedTimeImg.setVisibility(View.VISIBLE);
        }
    }

    private static String getlistaction(String orderCode) {
        String listaction = "";
        switch (orderCode) {
            case "开始出发":
                listaction = "到达现场";
                break;
            case "到达现场":
                listaction = "提交信息";
                break;
        }
        return listaction;
    }


    /***
     * 设置保存工单状态
     *
     * @param position
     */
    private void setOrderCode(int position, Button listactionBtn) {
        MaintenanceBean maintenanceBean = mainListBeen.get(position);
        int orderCode = maintenanceBean.getOrderCode();
        switch (orderCode) {
            case ORDER_STARTOFF:
                maintenanceBean.setDeparture_date(Util.getSystemDateNow());
                maintenanceBean.setOrderCode(ORDER_ARRIVE);
                maintenanceBean.setDeparture_longitude(lo);
                maintenanceBean.setDeparture_latitude(la);
                maintenanceBean.setIsDirty(1);
                maintenanceBean.update(maintenanceBean.getId());
                MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                maintenanceBeanTemp.setDeparture_date(Util.getSystemDateNow());
                maintenanceBeanTemp.setOrderCode(ORDER_ARRIVE);
                maintenanceBeanTemp.setDeparture_longitude(lo);
                maintenanceBeanTemp.setDeparture_latitude(la);
                maintenanceBeanTemp.setIsDirty(1);
                maintenanceBeanTemp.update(maintenanceBean.getId());

                mainListBeen.set(position, maintenanceBean);
                notifyDataSetChanged();
                EventBus.getDefault().post(new EventCenter.UpdateTime(maintenanceBean));
                break;
            case ORDER_ARRIVE:
                listactionBtn.setBackgroundResource(R.drawable.selector_listitem_buttongreen);
                maintenanceBean.setOnsite_date(Util.getSystemDateNow());
                maintenanceBean.setOrderCode(ORDER_SUBMITINFORMATION);
                maintenanceBean.setOnsite_latitude(la);
                maintenanceBean.setOnsite_longitude(lo);
                maintenanceBean.setIsDirty(1);
                maintenanceBean.update(maintenanceBean.getId());

                MaintenanceBean maintenanceBeanTemp2 = new MaintenanceBean();
                maintenanceBeanTemp2.setOnsite_date(Util.getSystemDateNow());
                maintenanceBeanTemp2.setOrderCode(ORDER_SUBMITINFORMATION);
                maintenanceBeanTemp2.setOnsite_latitude(la);
                maintenanceBeanTemp2.setOnsite_longitude(lo);
                maintenanceBeanTemp2.setIsDirty(1);
                maintenanceBeanTemp2.update(maintenanceBean.getId());

                mainListBeen.set(position, maintenanceBean);
                notifyDataSetChanged();
                EventBus.getDefault().post(new EventCenter.UpdateTime(maintenanceBean));
                break;
            default:
                gotoActivity(position);
                break;
        }

    }


    /***
     * 跳转到详情页
     *
     * @param position
     */
    private static void gotoActivity(int position) {
        Intent intent = new Intent();
        intent.putExtra("MaintenanceBean", mainListBeen.get(position));
        intent.putExtra("position", position);
        intent.setClass(context, MainDetailActivity.class);
        context.startActivity(intent);
    }

    private class MyOnClickListener implements View.OnClickListener {
        int position;
        TextView finishedTimeTv;
        ImageView finishedTimeImg;
        Button listactionBtn;

        public MyOnClickListener(int position, TextView finishedTimeTv, ImageView finishedTimeImg, Button listactionBtn) {
            this.position = position;
            this.finishedTimeTv = finishedTimeTv;
            this.finishedTimeImg = finishedTimeImg;
            this.listactionBtn = listactionBtn;
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.listactionBtn:
                    MaintenanceBean maintenanceBean = mainListBeen.get(position);
                    Integer orderCode = maintenanceBean.getOrderCode();
                    Log.i("log", "~~~orderCode = " + orderCode);
                    if (null != orderCode && (orderCode == ORDER_STARTOFF || orderCode == ORDER_ARRIVE)) {
                        //获取当前坐标
                        SharedPreferences mapPreferences = context.getSharedPreferences("SmecMntMapService",
                                Context.MODE_PRIVATE);
                        lo = mapPreferences.getString("lon", "未成功获取");
                        la = mapPreferences.getString("lat", "未成功获取");
                        String locationName = mapPreferences.getString("LocationName", "未成功获取");
                        double longitude;
                        double latitude;
                        try {
                            longitude = Double.parseDouble(maintenanceBean.getLongitude());
                            latitude = Double.parseDouble(maintenanceBean.getLatitude());
                        } catch (Exception e) {
                            longitude = 0;
                            latitude = 0;
                        }

                        if (mainListBeen.get(position).getOrderCode() == ORDER_ARRIVE) {
                            try {
                                Boolean isArrived;
                                Boolean isNO_COORDINATE = false;
                                if (longitude != 0 && latitude != 0) {
                                    isArrived = ServiceUtil.getCachelocation(context, longitude + "", latitude + "");
                                } else {
                                    isArrived = true;
                                    MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                                    maintenanceBeanTemp.setArrive_status(NO_COORDINATE);
                                    maintenanceBeanTemp.setIsDirty(1);

                                    maintenanceBeanTemp.update(maintenanceBean.getId());
                                    isNO_COORDINATE = true;
                                }

                                if (!isArrived) {
                                    Intent intent = new Intent(
                                            context,
                                            ElectronicFenceMapActivity.class);
                                    intent.putExtra("longitude", longitude);
                                    intent.putExtra("latitude", latitude);
                                    intent.putExtra("position", position);
                                    context.startActivity(intent);
                                    MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                                    maintenanceBeanTemp.setArrive_status(NOT_ARRIVED);
                                    maintenanceBeanTemp.setIsDirty(1);

                                    maintenanceBeanTemp.update(maintenanceBean.getId());
                                } else {
                                    String toastString = "";
                                    if (isNO_COORDINATE) {
                                        toastString = "\n\n当前电梯没有项目坐标，请通知站长维护(工单流程不受此影响，请继续操作)";
                                    } else {
                                        toastString = "\n\n成功到达现场";
                                    }
                                    new AlertView("提示", "\n当前地址：" + locationName + toastString, "取消", new String[]{"确定"}, null, context,
                                            AlertView.Style.Alert, new OnItemClickListener() {
                                        @Override
                                        public void onItemClick(Object o, int p) {
                                            if (p == 0) {
                                                finishedTimeTv.setText(Util.getSystemDate() + " 到达");
                                                finishedTimeImg.setVisibility(View.VISIBLE);
                                                listactionBtn.setText(getlistaction(listactionBtn.getText().toString()));
                                                setOrderCode(position, listactionBtn);
                                                EventBus.getDefault().post(new EventCenter.showBaffleDialog());
                                            }
                                        }
                                    }).show();
                                    MaintenanceBean maintenanceBeanTemp = new MaintenanceBean();
                                    maintenanceBeanTemp.setArrive_status(ARRIVED);
                                    maintenanceBeanTemp.setIsDirty(1);

                                    maintenanceBeanTemp.update(maintenanceBean.getId());
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else if (maintenanceBean.getOrderCode() == ORDER_STARTOFF) {
                            new AlertView("提示", "\n    确定开始出发？", "取消", new String[]{"确定"}, null, context,
                                    AlertView.Style.Alert, new OnItemClickListener() {
                                @Override
                                public void onItemClick(Object o, int p) {
                                    if (p == 0) {
                                        finishedTimeTv.setText(Util.getSystemDate() + " 出发");
                                        finishedTimeImg.setVisibility(View.VISIBLE);
                                        listactionBtn.setText(getlistaction(listactionBtn.getText().toString()));
                                        setOrderCode(position, listactionBtn);
                                    }
                                }
                            }).show();
                        } else {
                            new AlertView("提示", "\n当前地址：" + locationName, "取消", new String[]{"确定"}, null, context,
                                    AlertView.Style.Alert, new OnItemClickListener() {
                                @Override
                                public void onItemClick(Object o, int p) {
                                    if (p == 0) {
                                        finishedTimeTv.setText(Util.getSystemDate() + " 出发");
                                        finishedTimeImg.setVisibility(View.VISIBLE);
                                        listactionBtn.setText(getlistaction(listactionBtn.getText().toString()));
                                        setOrderCode(position, listactionBtn);
                                    }
                                }
                            }).show();
                        }

                    } else {
                        gotoActivity(position);
                    }
                    break;
            }
        }
    }

}